import html2canvas from 'html2canvas'
import { PDFDocument } from 'pdf-lib'
const disDownloadReport = ref(false)
const pageDataArr: any = ref([])
export async function downloadReports(fileName) {
  disDownloadReport.value = true
  document.documentElement.scrollLeft = 0
  document.documentElement.scrollTop = 0
  const docs = document.querySelectorAll('.reportPage:not(.hidden)')
  const totalDocs = docs.length
  const pdfDoc = await PDFDocument.create()
  pageDataArr.value = []
  const batchSize = 5
  const batches = Math.ceil(totalDocs / batchSize)
  for (let batch = 0; batch < batches; batch++) {
    const start = batch * batchSize
    const end = Math.min(start + batchSize, totalDocs)
    const batchPromises: any = []
    for (let i = start; i < end; i++) {
      batchPromises.push(htmlToCanvas(docs[i], i))
    }
    await Promise.all(batchPromises)
    for (let i = start; i < end; i++) {
      const imgBytes = await fetch(pageDataArr.value[i]).then((res) => res.arrayBuffer())
      const img = await pdfDoc.embedJpg(imgBytes)
      const page = pdfDoc.addPage([595.28, 841.89])
      const { width, height } = img.scaleToFit(595.28, 841.89)
      page.drawImage(img, {
        x: (page.getWidth() - width) / 2,
        y: (page.getHeight() - height) / 2,
        width,
        height
      })
    }
  }
  const pdfBytes = await pdfDoc.save()
  const blob = new Blob([pdfBytes], { type: 'application/pdf' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = fileName
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  disDownloadReport.value = false
}

function htmlToCanvas(doc, index) {
  return new Promise((resolve, reject) => {
    const box = window.getComputedStyle(doc)
    const width = Number(box.width)
    const height = Number(box.height)

    html2canvas(doc, {
      scale: window.devicePixelRatio * 1,
      width,
      height,
      scrollX: 0,
      scrollY: 0
    })
      .then((canvas) => {
        const pageData = canvas.toDataURL('image/jpeg', 1.0)
        pageDataArr.value[index] = pageData
        resolve(canvas)
      })
      .catch((error) => {
        console.error('Error generating canvas:', error)
        reject(error)
      })
  })
}
